//
//  MTCreatePartyMoneyCell.swift
//  MT
//
//  Created by ooops on 2020/5/25.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import Eureka
import MTCategory
import GrowingTextView
import RxSwift
import RxCocoa

public struct PartyGiftItemStruct {
    var itemName: String
    var count: Int
    var icon: String?
    var isSelected: Bool = false
    
    mutating func create(itemName: String, count: Int, icon: String?) -> PartyGiftItemStruct {
        self.itemName = itemName
        self.count = count
        self.icon = icon
        return self
    }
}

extension MTCreatePartyMoneyCell: MTPartyGiftSelectViewDelegate {
    func didTapCustomGiftCount(count: Int) {
        if count == 0 {
            contentTextField.isEnabled = true
            contentTextField.becomeFirstResponder()
        } else {
            self.row.value = "\(count)"
            self.contentTextField.text = row.displayValueFor?(row.value)
        }
    }
    
    func giftSelectDidRemoveFromSuperView() {
        contentTextField.isEnabled = false
        contentTextField.resignFirstResponder()
    }
}

public class MTCreatePartyMoneyCell: Cell<String>, CellType, UITextFieldDelegate {
    
    public func textFieldDidEndEditing(_ textField: UITextField) {
        textField.isEnabled = false
    }
    
    var partyResult: MiTuGiftModel?
    
    /// 显示模式
    lazy var tipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "名称"
        l.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return l
    }()
    
    lazy var customView: MTPartyGiftSelectView = {
        let v = MTPartyGiftSelectView()
        v.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
        return v
    }()
    
    /// 编辑模式
    lazy var contentTextField: UITextField = {
        let txf = UITextField()
        txf.textColor = UIColor.text.x9b9b9b
        txf.font = PingFangSCSemiboldFont(14)
        txf.clearButtonMode = .whileEditing
        //txf.keyboardAppearance = .dark
        txf.textAlignment = .right
        txf.isEnabled = false
        txf.delegate = self
        txf.keyboardType = .numberPad
        return txf
    }()
    
    lazy var customAccessoryView: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "icon_right_gary"))
//        imageV.isHidden = true
        //imageV.backgroundColor = .white
        return imageV
    }()
    
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        return v
    }()
    
    public var tipString: String? = nil
    public var contentString: String? = ""
    /// 输入框提示文字
    public var placeholder: String? {
        didSet {
            if placeholder != nil {
                let attribute: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : PingFangSCMediumFont(14),
                                                                 NSAttributedString.Key.foregroundColor : UIColor.text.x9b9b9b];
                contentTextField.attributedPlaceholder = NSAttributedString(string: placeholder!, attributes: attribute)
            }
        }
    }
    
    public var isHiddenAccessory: Bool = true {
        didSet {
            customAccessoryView.isHidden = isHiddenAccessory
        }
    }
    
    public var accessoryImage: String? {
        didSet {
            if accessoryImage != nil {
                customAccessoryView.image = UIImage(named: accessoryImage!)
            } else {
                customAccessoryView.image = nil
            }
        }
    }
    
    private var isHiddenLineView: Bool = true {
        didSet {
            lineView.isHidden = isHiddenLineView
        }
    }
    
    open override func cellCanBecomeFirstResponder() -> Bool {
        return true
    }

    open override func cellBecomeFirstResponder(withDirection direction: Direction) -> Bool {
        return true
    }

    open override func cellResignFirstResponder() -> Bool {
        return true
    }
    
    
    override public func setup() {
        super.setup()
        self.backgroundColor = UIColor.theme.background
        self.selectionStyle = .none
        self.textLabel?.isHidden = true
        self.detailTextLabel?.isHidden = true
        self.height = { UITableView.automaticDimension }
        setupUI()
        makeConstraint()
        if row.value != nil {
            contentTextField.text = row.displayValueFor?(row.value)
        }
        
        contentTextField.rx.text.orEmpty.changed.subscribe { text in
            let value: String = text.element!
            self.row.value = self.contentTextField.text
            /// 更新 cell
            self.row.updateCell()
        }.disposed(by: globalDisposedBag)
    }
    
    
    
    open override func didSelect() {
        super.didSelect()
//        row.deselect()
        self.formViewController()?.tableView.endEditing(true)
//        if contentTextField.isEnabled {
//            return
//        }
        customView.delegate = self
        let dataSource = [PartyGiftItemStruct(itemName: partyResult?.name ?? "", count: 300, icon: partyResult?.icon),
                            PartyGiftItemStruct(itemName: partyResult?.name ?? "", count: 1000, icon: partyResult?.icon),
                            PartyGiftItemStruct(itemName: partyResult?.name ?? "", count: 2000, icon: partyResult?.icon),
                            PartyGiftItemStruct(itemName: partyResult?.name ?? "", count: 5000, icon: partyResult?.icon),
                            PartyGiftItemStruct(itemName: partyResult?.name ?? "", count: 10000, icon: partyResult?.icon),
                            PartyGiftItemStruct(itemName: partyResult?.name ?? "", count: 10000, icon: partyResult?.icon)]
        
        let v = MTPartyGiftSelectView()
        v.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
        v.delegate = self
        self.customView = v
        
        self.customView.dataSource = dataSource
        self.present(animated: true, view: customView)
    }
    
    /// 展示弹窗
    public func present(animated: Bool = true, view: UIView) {
        //UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(self)
        if let p = UIApplication.mt_keyWindow?.rootViewController?.presentedViewController {
            p.view.addSubview(self)
        } else {
            UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(view)
        }
        
//        view.frame = CGRect(x: 0, y: ScreenHeight, width: ScreenWidth, height: ScreenHeight)
        
        UIView.animate(withDuration: animated ? 0.25 : 0, animations: {
            
            //view.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
            
        }) { (flag) in
            
        }
    }
    
    override public func update() {
        super.update()
        tipLabel.text = tipString
        
        if row.value != nil {
            contentTextField.text = row.displayValueFor?(row.value)
        }
    }
}

// MARK: - 布局相关
extension MTCreatePartyMoneyCell {
    
    private func setupUI() {
        contentView.addSubview(tipLabel)
        contentView.addSubview(contentTextField)
        contentView.addSubview(lineView)
        contentView.addSubview(customAccessoryView)
    }
    
    private func makeConstraint() {
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(0.5)
            make.bottom.equalToSuperview()
        }
        
        tipLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.width.greaterThanOrEqualTo(30)
        }
        
        contentTextField.snp.makeConstraints { (make) in
            make.right.equalTo(customAccessoryView.snp.left).offset(-8)
            make.left.equalTo(tipLabel.snp.right).offset(14)
            make.centerY.equalTo(tipLabel)
        }

        customAccessoryView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-8)
            make.centerY.equalTo(tipLabel)
            make.width.height.equalTo(15)
        }
    }
}


// The custom Row also has the cell: CustomCell and its correspond value
public final class MTCreatePartyMoneyCellRow: Row<MTCreatePartyMoneyCell>, RowType {
    required public init(tag: String?) {
        super.init(tag: tag)
        cellProvider = CellProvider<MTCreatePartyMoneyCell>.init()
    }
}

